package net.zdsoft.wpchat.support.service.impl;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import net.zdsoft.keel.cache.Cache;
import net.zdsoft.wpchat.android.client.Constant;
import net.zdsoft.wpchat.support.dao.SysOptionDao;
import net.zdsoft.wpchat.support.entity.SysOption;
import net.zdsoft.wpchat.support.service.SysOptionService;

@Service
public class SysOptionServiceImpl implements SysOptionService {
    protected Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private SysOptionDao sysOptionDao;
    @Resource
    private Cache<String, Object> cache;

    @Override
    public Map<String, String> getSysOptions() {
        Map<String, String> name2ValueMap = (Map<String, String>) cache.get(Constant.CACHE_KEY_OF_SYS_OPTION);

        logger.debug("SysOptions:" + name2ValueMap);
        if (null == name2ValueMap) {
            name2ValueMap = sysOptionDao.findName2ValueMap();
            cache.put(Constant.CACHE_KEY_OF_SYS_OPTION, name2ValueMap, Constant.INTERVAL_OF_REFRESH_CACHE_HOUR_LONGER,
                    TimeUnit.HOURS);

        }

        return name2ValueMap;
    }

    @Override
    public String getPhoneMobileRegex() {
        String regex = getSysOptions().get(Constant.GLOBAL_PHONE_TYPE_REGEX_MOBILE);
        return regex != null && !"".equals(regex) ? regex : "(1(3[4-9]|4[7]|5[012789]|8[2378])\\d{8})|(0001\\d{8})";
    }

    @Override
    public String getPhoneUnicomRegex() {
        String regex = getSysOptions().get(Constant.GLOBAL_PHONE_TYPE_REGEX_UNICOM);
        return regex != null && !"".equals(regex) ? regex : "(1(3[0-2]|5[56]|8[56])\\d{8})|(0002\\d{8})";
    }

    @Override
    public String getPhoneTelecomRegex() {
        String regex = getSysOptions().get(Constant.GLOBAL_PHONE_TYPE_REGEX_TELECOM);
        return regex != null && !"".equals(regex) ? regex
                : "(?!00|015|013)(0\\d{9,11})|(0003\\d{8})|(1(33|53|89)\\d{8})";
    }

    @Override
    public List<SysOption> getAllSysOption() {
        return sysOptionDao.findAllSysOptions();
    }

    @Override
    public void modifySysOption(SysOption sysOption) {
        sysOptionDao.updateSysOption(sysOption);
    }

    @Override
    public void removeOption(String id) {
        sysOptionDao.deleteSysOptionByIds(id);
    }

    @Override
    public void addOption(SysOption sysOption) {
        sysOptionDao.insertSysOption(sysOption);
    }

}
